﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Collections;

namespace Bonobo.Reader
{
    internal class BonoboItemProviderLoader
    {
        private static BonoboItemProviderLoader _loader;

        public List<BonoboItemProvider> Providers { get; set; }

        private BonoboItemProviderLoader()
        {
            Providers = GetPlugins<BonoboItemProvider>("Plugins");
        }

        public static BonoboItemProviderLoader GetInstance()
        {
            if (_loader == null)
            {
                return new BonoboItemProviderLoader();
            }
            else
            {
                return _loader;
            }
        }

        public List<T> GetPlugins<T>(string folder)
        {
            String[] files = Directory.GetFiles(folder, "*.dll");

            List<T> tList = new List<T>();

            foreach (String file in files)
            {
                Assembly assembly = Assembly.LoadFrom(Directory.GetParent(Assembly.GetExecutingAssembly().Location).FullName + "\\" +file);

                foreach (Type type in assembly.GetTypes())
                {
                    if (!type.IsClass || type.IsNotPublic)
                    {
                        continue;
                    }

                    if (type.BaseType == typeof(T))
                    {
                        object obj = Activator.CreateInstance(type);
                        T t = (T)obj;
                        tList.Add(t);
                    }

                }
            }

            return tList;
        }

    }
}
